package com.flight.model.dao.impl;

import com.flight.model.dao.PassengerDAO;
import com.flight.model.entity.Passenger;
import com.flight.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PassengerDAOImpl implements PassengerDAO {
    @Override
    public Passenger getByPassengerId(String passengerId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        Passenger passenger = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM passenger WHERE passenger_id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, passengerId);
            rs = stmt.executeQuery();
            if (rs.next()) {
                passenger = new Passenger();
                passenger.setPassengerId(rs.getString("passenger_id"));
                passenger.setUsername(rs.getString("username"));
                passenger.setPhone(rs.getString("phone"));
                passenger.setPassword(rs.getString("password"));
                passenger.setRealName(rs.getString("real_name"));
                passenger.setAddress(rs.getString("address"));
                passenger.setCreateTime(rs.getDate("create_time"));
                passenger.setUpdateTime(rs.getDate("update_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }
        return passenger;
    }

    @Override
    public boolean addPassenger(Passenger passenger) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO passenger(passenger_id, username, phone, password, real_name, address) VALUES (?, ?, ?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, passenger.getPassengerId());
            stmt.setString(2, passenger.getUsername());
            stmt.setString(3, passenger.getPhone());
            stmt.setString(4, passenger.getPassword());
            stmt.setString(5, passenger.getRealName());
            stmt.setString(6, passenger.getAddress());
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, stmt, null);
        }
    }
}